﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Script.Serialization;

namespace doufu.Common.Extensen
{
    static public class JsonExtension
    {
        static public string GetString<T>(this Dictionary<T, T> src)
        {
            return src.Aggregate(string.Empty, (current, keyValuePair) => current + "_" + string.Format("{0}:{1}", keyValuePair.Key, keyValuePair.Value));
        }

        /// <summary>
        /// 把对像转为string
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="src"></param>
        /// <returns></returns>
        static public string ToJson<T>(this T src) where T : class
        {
            if (src == null) return string.Empty;
            var serialize = new JavaScriptSerializer();
            return serialize.Serialize(src);
        }

        /// <summary>
        /// 把字符串转为相应对像
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="src"></param>
        /// <returns></returns>
        static public T FromJson<T>(this string src)
        {
            T t;
            if (!string.IsNullOrEmpty(src))
            {
                var serialize = new JavaScriptSerializer();
                t = serialize.Deserialize<T>(src);
            }
            else
            {
                t = default(T);
            }
            return t;
        }
    }
}